﻿using llm_net.Models;
using llm_net.Services.Abstractions;
using llm_project.Infrastructure.Helpers;
using llm_project.Models;
using llm_project.Services.Implementations;
using Microsoft.AspNetCore.Builder.Extensions;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
using System.Collections.Concurrent;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using static llm_net.Infrastructure.Extensions.ServiceCollectionExtensions;
using static llm_net.Services.Implementations.TongyiApiService;
namespace llm_net.Services.Implementations
{
    public class UserTagService : IUserTagService
    {
       
        private readonly ILogger<TongyiApiService> _logger;
        private readonly LlmApiClient _llmApiClient;
        private readonly TongyiApiOptions _apiOptions;
        // 全局标签池（线程安全，使用静态集合）
        private static readonly ConcurrentDictionary<string, byte> _globalTagPool = new(); // 线程安全全局标签池
        private static readonly object _tagPoolLock = new object(); // 线程安全锁
        public UserTagService(HttpClient httpClient, IConfiguration configuration, ILogger<TongyiApiService> logger, LlmApiClient llmApiClient, IOptions<TongyiApiOptions> apiOptions)
        {
            _apiOptions= apiOptions.Value;
            _logger = logger;
            _llmApiClient = llmApiClient;
            // 初始化HttpClient头部配置
            HttpClientSingleton.ConfigureApiHeaders(_apiOptions.AppKey);
        }

        /// <summary>
        /// 生成单个用户标签
        /// </summary>
        public async Task<List<TagWithWeightDto>> GenerateUserTagsAsync(UserBehaviorReq behavior)
        {
            if (behavior?.Actions == null || !behavior.Actions.Any())
                throw new ArgumentException("用户行为数据不能为空");

            // 构建Prompt -> 调用LLM -> 解析结果
            var prompt = TagUtils.BuildSinglePrompt(behavior.Actions);
            var rawTags = await _llmApiClient.CallLlmApiAsync(prompt);
            var parsedTags = TagUtils.ParseSingleTags(rawTags);

            // 更新全局标签池
            parsedTags.ForEach(t => _globalTagPool.TryAdd(t.Label, 0));

            return parsedTags.Select(t => new TagWithWeightDto
            {
                Label = t.Label,
                Weight = (float)Math.Round(t.Weight, 2)
            }).ToList();
        }

        /// <summary>
        /// 批量生成用户标签
        /// </summary>
        public async Task<Dictionary<string, List<TagWithWeightDto>>> GenerateBatchUserTagsAsync(BatchUserBehaviorReq batchRequest)
        {
            if (batchRequest?.UserBehaviors == null || !batchRequest.UserBehaviors.Any())
                throw new ArgumentException("批量用户行为数据不能为空");

            // 构建批量Prompt -> 调用LLM -> 解析结果
            var prompt = TagUtils.BuildBatchPrompt(batchRequest.UserBehaviors);
            var rawTags = await _llmApiClient.CallLlmApiAsync(prompt);
            var parsedTags = TagUtils.ParseBatchTags(rawTags, _logger);

            // 转换结果并更新全局标签池
            var result = new Dictionary<string, List<TagWithWeightDto>>();
            foreach (var (userId, tags) in parsedTags)
            {
                tags.ForEach(t => _globalTagPool.TryAdd(t.Label, 0));
                result[userId] = tags.Select(t => new TagWithWeightDto
                {
                    Label = t.Label,
                    Weight = (float)Math.Round(t.Weight, 2)
                }).ToList();
            }

            return result;
        }

        /// <summary>
        /// 获取全局标签池
        /// </summary>
        public List<string> GetGlobalTagPool() => _globalTagPool.Keys.ToList();

        /// <summary>
        /// 标签转换为向量
        /// </summary>
        public double[] ConvertTagsToVector(List<(string Label, double Weight)> tagsWithWeights)
        {
            var tagPool = GetGlobalTagPool();
            return tagPool.Select(tag =>
                tagsWithWeights.FirstOrDefault(t => t.Label == tag).Weight
            ).ToArray();
        }
    }
}
